package common

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
	"time"
)

type Caches struct {
}

//文件初始化
func initFile() cache.Cache {
	on := beego.AppConfig.String("file_on")
	if on != "on" {
		Logs("文件缓存功能未开启")
		return nil
	}
	path := beego.AppConfig.String("file_path")
	suffix := beego.AppConfig.String("file_suffix")
	level := beego.AppConfig.String("file_dir_level")
	expiry := beego.AppConfig.String("file_expiry")
	con := `{"CachePath":"` + path + `","FileSuffix":"` + suffix + `","DirectoryLevel":"` + level + `","EmbedExpiry":"` + expiry + `"}`
	bc := cache.NewFileCache()
	_ = bc.StartAndGC(con)
	return bc
}

//redis缓存初始化
func initRedis() cache.Cache {
	on := beego.AppConfig.String("redis_on")
	if on != "on" {
		Logs("redis缓存功能未开启")
		return nil
	}
	key := beego.AppConfig.String("redis_key")
	rc := beego.AppConfig.String("redis_conn")
	num := beego.AppConfig.String("redis_num")
	password := beego.AppConfig.String("redis_password")
	conn := `{"key":"` + key + `","conn":"` + rc + `","dbNum":"` + num + `","password":"` + password + `"}`
	bc, _ := cache.NewCache("redis", conn)
	return bc
}

//设置文件缓存
func (c *Caches) SetFileCache(key string, val interface{}, duration time.Duration) {
	bc := initFile()
	if bc != nil {
		err := bc.Put(key, val, duration)
		if err != nil {
			Logs(key + ":缓存存储失败")
		}
	}
}

//判断是否存在
func (c *Caches) ExistFileCache(key string) bool {
	bc := initFile()
	if bc != nil {
		return bc.IsExist(key)
	}
	return false
}

//删除缓存信息
func (c *Caches) DeleteFileCache(key string) bool {
	bc := initFile()
	if bc != nil && bc.Delete(key) != nil {
		return false
	}
	return true
}

//获取文件缓存
func (c *Caches) GetFileCache(key string) interface{} {
	bc := initFile()
	if bc != nil {
		return bc.Get(key)
	}
	return nil
}

//redis设置缓存
func (c *Caches) SetRedisCache(key string, val interface{}, duration time.Duration) {
	bc := initRedis()
	if bc != nil {
		err := bc.Put(key, val, duration)
		if err != nil {
			Logs(key + ":缓存存储失败")
		}
	}
}

//获取redis信息
func (c *Caches) GetRedisCache(key string) interface{} {
	bc := initRedis()
	if bc != nil {
		return bc.Get(key)
	}
	return nil
}

//判断是否存在
func (c *Caches) ExistRedisCache(key string) bool {
	bc := initRedis()
	if bc != nil {
		return bc.IsExist(key)
	}
	return false
}

//删除缓存信息
func (c *Caches) DeleteRedisCache(key string) bool {
	bc := initRedis()
	if bc != nil && bc.Delete(key) != nil {
		return false
	}
	return true
}
